package com.example.demo03_mvm.viewmodel;

import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.SearchView;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.LifecycleOwner;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.JsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.demo03_mvm.App;
import com.example.demo03_mvm.R;
import com.example.demo03_mvm.adapter.XHAdapter;
import com.example.demo03_mvm.databinding.ActivityDetailBinding;
import com.example.demo03_mvm.model.AddCartEntity;
import com.example.demo03_mvm.model.GoodDetailEntity;
import com.example.demo03_mvm.model.GoodsEntity;
import com.example.demo03_mvm.repos.CartRepso;
import com.example.demo03_mvm.repos.GoodsTypeRepos;
import com.example.demo03_mvm.utils.LoginCheck;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.gson.Gson;
import com.youth.banner.Banner;
import com.youth.banner.loader.ImageLoader;

import org.aspectj.lang.annotation.Around;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.RequestBody;


public class DetailViewModel extends BaseViewModel{
    TextView tv_check;
    EditText ed_num;
    GoodDetailEntity.DataBean bean;
    ArrayList<String> strings;

    public DetailViewModel(@NonNull Application application) {
        super(application);
    }

    public void getDetail(int gid, ActivityDetailBinding binding, LifecycleOwner owner){
        tv_check=binding.tvCheckxh;

        GoodsTypeRepos typeRepos = new GoodsTypeRepos();
        MutableLiveData<GoodDetailEntity> detail = typeRepos.getGoodDetail(gid);
        detail.observe(owner, new Observer<GoodDetailEntity>() {
            @Override
            public void onChanged(GoodDetailEntity goodsEntity) {
                bean = goodsEntity.getData();
//                binding.setVariable(BR.goodde,bean);
                binding.setGoodde(bean);
                Log.i("===",goodsEntity.toString());
                initBanner(bean.getBannerList(),binding.banner);
                String json = bean.getGoods_attribute();

                JSONArray array = JsonUtils.getJSONArray(json, "配置", new JSONArray());
                strings = new ArrayList<>();
                for (int i = 0; i < array.length(); i++) {
                    try {
                        strings.add(array.get(i).toString());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                tv_check.setText(strings.get(0)+",1件");
            }
        });
    }

    public void onClick(View view){
        View view1 = LayoutInflater.from(App.getContext()).inflate(R.layout.pop_detail, null);
        ImageView iv = view1.findViewById(R.id.iv_goodspop);
        Glide.with(iv).load(bean.getGoods_default_icon()).into(iv);
        TextView tv = view1.findViewById(R.id.tv_pricepop);
        TextView tv_del=view1.findViewById(R.id.tv_del);
        TextView tv2 = view1.findViewById(R.id.tv_add);
        tv.setText(String.valueOf(bean.getGoods_default_price()));

        ed_num=view1.findViewById(R.id.ed_num);
        String s = tv_check.getText().toString();
        String[] split = s.split(",");
        String s1 = split[1].substring(0, split[1].length() - 1);
        Log.i("===件",s1);
        ed_num.setText(s1);

        PopupWindow window = new PopupWindow(view1, ViewGroup.LayoutParams.MATCH_PARENT, 500, true);
        window.showAtLocation(view, Gravity.BOTTOM,0,0);


        RecyclerView rv = view1.findViewById(R.id.rv_xh);
        XHAdapter adapter = new XHAdapter(R.layout.item_xh, strings);
        rv.setAdapter(adapter);
        //流式布局
        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(App.getContext());
        layoutManager.setFlexDirection(FlexDirection.ROW);
        rv.setLayoutManager(layoutManager);


        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                tv_check.setText(strings.get(position));
            }
        });

        tv_del.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String num=ed_num.getText().toString();
                int count=Integer.parseInt(num);
                if (count>=2){
                    count--;
                    ed_num.setText(String.valueOf(count));
                    ed_num.setText(String.valueOf(count));
                    tv_check.setText(tv_check.getText().toString().replaceFirst(",[0-9]+件",","+count+"件"));
                }else{
                    ToastUtils.showLong("数量不可以小于1");
                }
            }
        });
        tv2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String num = ed_num.getText().toString();
                int count = Integer.parseInt(num);
                if(count<bean.getGoods_stock_count()){
                    count++;
                    ed_num.setText(String.valueOf(count));
                    tv_check.setText(tv_check.getText().toString().replaceFirst(",[0-9]+件",","+count+"件"));
                }else {
                    ToastUtils.showLong("最大数量");
                }
            }
        });
    }

    private void initBanner(List<String> bannerList, Banner banner) {
        banner.setImages(bannerList);
        banner.setImageLoader(new ImageLoader() {
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        banner.start();
    }

    @LoginCheck
    public void addCart(int gid,LifecycleOwner owner){
        Log.i("===","addCart-已登录了");
        String s = tv_check.getText().toString();
        String[] split = s.split(",");
        String s1 = split[1].substring(0, split[1].length() - 1);
        HashMap<String, Integer> map = new HashMap<>();
        map.put("goods_id",gid);
        map.put("count",Integer.parseInt(s1));
        String json = new Gson().toJson(map);
        RequestBody body = RequestBody.create(MediaType.parse("application/json"), json);

        new CartRepso().addCart(body).observe(owner, new Observer<AddCartEntity>() {
            @Override
            public void onChanged(AddCartEntity addCartEntity) {
                if(addCartEntity.getCode()==200){
                    ToastUtils.showLong("加入购物车成功");
                    ARouter.getInstance().build("/app/MainActivity").navigation();
                }
            }
        });
    }
}
